<?php
require_once '../../server/utils/functions.php';
require_once '../../server/model/Salle.php';
require_once '../../server/model/Machine.php';
$db = db();
$query = Array();
$parameters = Array();
if(isset($_GET["name"])&& !empty($_GET["name"])){
    $parameters["name"] = utf8_decode(htmlentities($_GET["name"]));
    $query[] = " SAL_NOM=:name";
}    
if(isset($_GET["id"])&& !empty($_GET["id"])){
    $parameters["id"] = utf8_decode(htmlentities($_GET["id"]));
    $query[] = " SAL_ID=:id";
}    
$where = "";
if(sizeof($query)>0){
    $where.=" WHERE";
    $i = 0;
    foreach($query as $condition){
        if($i!=0){
            $where .= " AND";
        }
        $where .= $condition;
        $i++;
    }
}
$req = $db->prepare("SELECT SAL_ID,SAL_NOM, SAL_INFOS FROM SALLE".$where);
$req->execute($parameters);
$response = Array();

while($datas = $req->fetch()){
    $machines = Array(); 
    $req2 = $db->prepare("SELECT MAC_ID, MAC_IP_ADDR, MAC_INFOS, MAC_RAM, MAC_DISK FROM MACHINE WHERE SAL_ID=?");
    $req2->execute(Array($datas["SAL_ID"]));
    while($datas2 = $req2->fetch()){
        $machine = new Machine($datas2["MAC_IP_ADDR"], utf8_encode($datas2["MAC_INFOS"]), $datas2["MAC_RAM"], $datas2["MAC_DISK"]);
        $machine->setId($datas2["MAC_ID"]);
        $machines[] = $machine;
    }
    $salle = new Salle(utf8_encode($datas["SAL_NOM"]), utf8_encode($datas["SAL_INFOS"]), $machines);
    $salle->setId($datas["SAL_ID"]);
    $response[]=$salle;
    $req2->closeCursor();
}
if(isset($_GET["type"]) && $_GET["type"]=="xml"){
//    $xml = new SimpleXMLElement('<salles/>');
    $domtree = new DOMDocument('1.0', 'UTF-8');
    $xmlRoot = $domtree->createElement("salles");
    foreach ($response as $salle) {
        $xmlRoot->appendChild($salle->xmlSerialize($domtree));
    }
    $domtree->appendChild($xmlRoot);

    Header('Content-type: text/xml');
    echo $domtree->saveXML();
}else{
    Header('Content-type: text/json');
    echo json_encode($response);
}
$req->closeCursor();
?>
